<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Workbench;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;
use MoChat\Plugin\ContactStage\Contract\ContactStageEmployeeContract;
use MoChat\Plugin\ContactTrack\Constants\Event;
use MoChat\Plugin\ContactTrack\Constants\EventName;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 客户详情 - 编辑跟进状态.
 *
 * Class StageUpdate
 * @Controller
 */
class StageUpdate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Inject
     * @var ContactStageEmployeeContract
     */
    protected $contactStageEmployeeService;

    /**
     * @Inject
     * @var ContactStageContract
     */
    private $contactStageSerice;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $contactTrackService;

    /**
     * 联系人表.
     * @Inject
     * @var WorkContactContract
     */
    private $workContactService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactFollow/stageUpdate", methods="PUT")
     * @return array
     */
    public function handle()
    {
        // 接收参数
        $params['contactId'] = (int) $this->request->input('contactId');
        $params['statusId'] = (int) $this->request->input('statusId');
        $user = user();
        $params['employeeId'] = $user['id'];
        $params['corpId'] = $user['corpId'];

        // 校验参数
        $this->validated($params);
        // 记录轨迹
        $process = $this->contactStageSerice->getContactStageById($params['statusId']);
        $content = '编辑用户跟进状态：' . $process['name'];
        // 数据操作
        Db::beginTransaction();
        try {
            $this->recordTrack($params['contactId'], Json::encode($content));
            // 编辑用户跟进状态
            $this->workContactService->updateWorkContactById($params['contactId'], ['follow_up_status' => $params['statusId']]);
            // 阶段自动化
            $contactStage = $this->contactStageEmployeeService->getContactStageEmployeeByOtherId($params['contactId'], $params['employeeId'], $params['corpId'], ['id']);
            if (empty($contactStage)) {
                $createData = [
                    'corp_id' => $params['corpId'],
                    'stage_id' => $params['statusId'],
                    'contact_id' => $params['contactId'],
                    'employee_id' => $params['employeeId'],
                    'remind_status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $this->contactStageEmployeeService->createContactStageEmployee($createData);
            } else {
                $this->contactStageEmployeeService->updateContactStageEmployeeById($contactStage['id'], ['stage_id' => $params['statusId']]);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '编辑用户跟进状态失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }

        return [];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'contactId' => 'required',
            'statusId' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'contactId.required' => '客户id必传',
            'statusId.required' => '跟进状态id必传',
        ];
    }

    /**
     * 记录轨迹.
     * @param $contactId
     * @param $content
     */
    private function recordTrack($contactId, $content)
    {
        $jsonContact = [
            'title' => EventName::PROCESS_STATUS,
            'content' => $content,
        ];
        $data = [
            'employee_id' => user()['id'],
            'contact_id' => $contactId,
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'event' => Event::PROCESS_STATUS,
        ];

        $res = $this->contactTrackService->createContactTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
